package com.uni.service;

import com.aliyun.oss.OSS;

import com.uni.config.AliyunConfig;
import com.uni.pojo.FileUploadResult;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class FileUploadService {
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{"bmp", "jpg",
            "jpeg", "gif", "png"};
    public final static String ERROR = "error";
    public final static String DONE = "done";
    public final static String SUCCESS = "success";
    @Autowired
    private OSS ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;

    public FileUploadResult upload(String uploadFile, Long prodId) {

        Pattern pattern = Pattern.compile("image/(.*);");
        Matcher matcher = pattern.matcher(uploadFile);
        String uploadType = matcher.find() ? matcher.group(1) : null;
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {

            if (type.equals(uploadType)) {
                isLegal = true;
                break;
            }
        }
        //封装Result对象，并且将文件的byte数组放置到result对象中
        FileUploadResult fileUploadResult = new FileUploadResult("error");
        if (!isLegal) {
            return fileUploadResult;
        }
        //文件新路径
        String filePath = getFilePath(prodId, uploadType);
        // 上传到阿里云
        try {
            // 上传时需去掉base64编码的data:image/xxx;base64前缀
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(Base64Utils.decodeFromString(uploadFile.replace(' ', '+').split(",")[1].trim())));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus(ERROR);
            return fileUploadResult;
        }
        fileUploadResult.setStatus(DONE);
        fileUploadResult.setResponse(SUCCESS);
        String fileUrl = this.aliyunConfig.getUrlPrefix() + filePath;
        fileUploadResult.setName(fileUrl);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    private String getFilePath(Long prodId, String fileType) {
        DateTime dateTime = new DateTime();
        return "images/product/" + prodId + "/" + dateTime.toString("yyyy-MM-dd")
                + System.currentTimeMillis() + "." +
                fileType;
    }

}
